package cn.cms.mongo;

import cn.cms.constants.Constants;
import cn.cms.util.SqlUtil;
import cn.cms.util.StringUtil;
import org.jfaster.mango.binding.BoundSql;
import org.jfaster.mango.interceptor.Parameter;
import org.jfaster.mango.interceptor.UpdateInterceptor;
import org.jfaster.mango.util.jdbc.SQLType;

import javax.sql.DataSource;
import java.util.Iterator;
import java.util.List;

/**
 * Created by justin on 2017/12/22.
 */
@Deprecated
public class MysqlUpdateInterceptor extends UpdateInterceptor {
    @Override
    public void interceptUpdate(BoundSql boundSql, List<Parameter> parameters, SQLType sqlType, DataSource dataSource) {
        if (sqlType == SQLType.UPDATE) {
            if (parameters != null & parameters.size() == 2) {
                Iterator var4 = parameters.iterator();
                Boolean flag = false;
                Object model = null;
                while (var4.hasNext()) {
                    Parameter parameter = (Parameter) var4.next();
                    Object val = parameter.getValue();
                    if (val.equals(Constants.NEED_UPDATE_INTERCEPTOR)) {
                        flag = true;
                    }else {
                        model = val;
                    }
                }
                if(flag){
                    try {
                        String sqlPart = SqlUtil.getUpdateSqlPart(model,boundSql.getSql());
                        this.handleSql(boundSql,sqlPart);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    void handleSql(BoundSql boundSql,String sqlPart) {
        String sql = boundSql.getSql();
        if(!StringUtil.isSpaceOrNull(sqlPart)){
            String table = SqlUtil.getUpdateSqlTable(sql);
            String condition = sql.split(" where ")[1];
            boundSql.setSql("update " + table + " set " + sqlPart + " where " + condition);
        }
    }
}
